-- utilies for processing a FCGI request
package.path = './lib/?.lua;./lib/?/init.lua;./vendor/?.lua;./vendor/?/init.lua;' .. package.path

local lf = require("afu.luafcgid")
local string_match = string.match
local mod
function main(env, con)

    local request = require "afu.request"
    local req = request.Request:new(env, con)
    local response = require "afu.response"
    local resp = response.Response:new(env, con)
    
	local c = require "config"
	local router = c.router or {}
    for   _, route in pairs(router) do
        local mod_name, fn = string_match(route[2], '^(.+)%.([^.]+)$') --匹配函数
        --con:puts(req.path .. route[2])
        matches = {req.path:match(route[1])}-- 正则匹配url
        if #matches > 0 then
        	
            mod = require(mod_name)
            local func = mod[fn]
            if func then       
                local ok, ret = pcall(func, req, resp)
                if not ok then resp:error(ret) end
                resp:finish()          
            else
                local error_info = "请求url:" .. req.uri .. " 对应的函数'" .. mod_name .. "." .. fn .. "' 不存在 "
       			con:log(error_info)
            end         
            --exit = view(match) or ngx.HTTP_OK
            --ngx.exit( ngx.HTTP_OK )
        end
    end
	--con:puts(string.format("<textarea>%s</textarea>", con:gets()))
    -- no match, return 404
	con:puts("<pre>\n")
	for n, v in pairs(req.uri_args) do
		con:puts(string.format("%s = %s\n", n, v ))
	end
    con:puts("</pre>\n")
   --[[	

	if env.REQUEST_METHOD == "GET" then
		s = {}  -- string sets are faster then calling req:puts() all the time
		params = lf.parse(env.QUERY_STRING)
		table.insert(s, "<h1>GET Params</h1><pre>\n")
		for n, v in pairs(params) do
			table.insert(s, string.format("%s = %s\n", n, v))
		end
		table.insert(s, "</pre>\n")
		con:puts(table.concat(s))
	end

	if env.REQUEST_METHOD == "POST" then
		con:puts("<h1>POST</h1>\n")
		con:puts(string.format("<textarea>%s</textarea>", con:gets()))
	end
	--]]
end
